package dev;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * Author :  Rocky
 * Date : 04/06/2017 22:00
 * Description :
 * Test :
 */
public class MiscUtils {

    private static final PooledByteBufAllocator pbba = new PooledByteBufAllocator(true);

    //直接内存或者堆内存的的最大值
    private static final int DIRECT_BUFFER_MAX_SIZE = 50 * 1024 * 1024;

    public static int toUnsignedInt(byte x) {
        return (x) & 0xff;
    }

    public static int toUnsignedInt(short x) {
        return (x) & 0xffff;
    }

    public static long toUnsignedLong(int x) {
        return (x) & 0xffffffffL;
    }

    public static ByteBuf directBuffer(int initCapacity) {
        return pbba.directBuffer(initCapacity, DIRECT_BUFFER_MAX_SIZE);
    }

    public static ByteBuf heapBuffer(int initCapacity) {
        return pbba.buffer(initCapacity, DIRECT_BUFFER_MAX_SIZE);
    }


    public static void writeMedium(ByteBuffer bb, int value) {
        bb.put((byte) (value >>> 16));
        bb.put((byte) (value >>> 8));
        bb.put((byte) value);
    }

    public static int readMedium(ByteBuffer bb) {
        int value = readUnsignedMedium(bb);
        if ((value & 0x800000) != 0) {
            value |= 0xff000000;
        }
        return value;
    }

    public static int readUnsignedMedium(ByteBuffer bb) {
        return (bb.get() & 0xff) << 16 |
                (bb.get() & 0xff) << 8 |
                bb.get() & 0xff;
    }

    public static String getMd5ByFile(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }
}
